const winston = require('winston');
const path = require('path');
const dbLogger = require('../middleware/logToDatabase');

// 定义日志格式
const logFormat = winston.format.combine(
  winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
  winston.format.errors({ stack: true }),
  winston.format.splat(),
  winston.format.json()
);

// 创建logger实例
const logger = winston.createLogger({
  level: process.env.LOG_LEVEL || 'info',
  format: logFormat,
  transports: [
    // 错误日志
    new winston.transports.File({
      filename: path.join(__dirname, '../../logs/error.log'),
      level: 'error',
      maxsize: 5242880, // 5MB
      maxFiles: 5
    }),
    // 所有日志
    new winston.transports.File({
      filename: path.join(__dirname, '../../logs/combined.log'),
      maxsize: 5242880,
      maxFiles: 5
    })
  ]
});

// 开发环境添加控制台输出
if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({
    format: winston.format.combine(
      winston.format.colorize(),
      winston.format.simple()
    )
  }));
}

// 🔥 包装原始方法，自动写入数据库
const originalInfo = logger.info.bind(logger);
const originalError = logger.error.bind(logger);
const originalWarn = logger.warn.bind(logger);
const originalDebug = logger.debug.bind(logger);

logger.info = function(message, ...args) {
  originalInfo(message, ...args);
  // 🔥 写入数据库
  const meta = args[0] || {};
  dbLogger.addSystemLog('info', meta.action || 'general', message, {
    userId: meta.userId,
    userType: meta.userType,
    ipAddress: meta.ipAddress,
    userAgent: meta.userAgent
  });
};

logger.error = function(message, ...args) {
  originalError(message, ...args);
  // 🔥 写入数据库
  const meta = args[0] || {};
  const errorMessage = typeof message === 'string' ? message : (message.message || JSON.stringify(message));
  dbLogger.addSystemLog('error', meta.action || 'error', errorMessage, {
    userId: meta.userId,
    userType: meta.userType,
    ipAddress: meta.ipAddress,
    userAgent: meta.userAgent
  });
};

logger.warn = function(message, ...args) {
  originalWarn(message, ...args);
  // 🔥 写入数据库
  const meta = args[0] || {};
  dbLogger.addSystemLog('warning', meta.action || 'general', message, {
    userId: meta.userId,
    userType: meta.userType,
    ipAddress: meta.ipAddress,
    userAgent: meta.userAgent
  });
};

logger.debug = function(message, ...args) {
  originalDebug(message, ...args);
  // 🔥 写入数据库（debug日志也记录）
  const meta = args[0] || {};
  dbLogger.addSystemLog('debug', meta.action || 'general', message, {
    userId: meta.userId,
    userType: meta.userType,
    ipAddress: meta.ipAddress,
    userAgent: meta.userAgent
  });
};

// 导出数据库日志器以供直接使用
logger.dbLogger = dbLogger;

module.exports = logger;
